import { CreateOrderParamType, GetOrderListParamType, OrderItemType, OrderListType } from "@Tea/model"
import { AppTokenObj } from "../dao/AppToken"
import { renderInsertSql, renderSelectParam, renderSelectSql } from "../utils/renderSql"
import { ReposBase } from "./RepoBase"
import { v4 as uuidv4 } from "uuid"

export class OrderRepository extends ReposBase {
  private static inst: OrderRepository

  public static getInstance() {
    if (!OrderRepository.inst) {
      OrderRepository.inst = new OrderRepository()
    }

    return OrderRepository.inst
  }

  // 创建订单
  async createOrder(customer: AppTokenObj['userId'], address: CreateOrderParamType["address"]) {
    const orderNo = uuidv4()
    const sql = renderInsertSql({
      database: 'orders',
      keyAndVal: [
        { key: 'order_id', value: orderNo },
        { key: 'create_time', value: new Date() },
        { key: 'customer', value: customer },
        { key: 'state', value: '待支付' },
        { key: 'address_json', value: typeof address === 'string' ? address : JSON.stringify(address) }
      ],
    })

    return {
      result: await this.insert(sql),
      orderNo
    }
  }

  cancelOrder(orderId: string) {
    const sql = `DELETE FROM orders WHERE order_id = '${orderId}'`

    return this.delete(sql)
  }

  pay(orderId: string) {
    const sql = `UPDATE orders SET state = '待确认' WHERE order_id = '${orderId}' AND state = '待支付'`

    return this.update(sql)
  }

  confirm(orderId: string) {
    const sql = `UPDATE orders SET state = '已完成' WHERE order_id = '${orderId}' AND state = '待确认'`
    console.log(sql);

    return this.update(sql)
  }

  async orderList(state: GetOrderListParamType["state"], customer: AppTokenObj["userId"]) {
    const config: renderSelectParam = {
      database: [
        { name: "orders", aliasName: 'o' }
      ],
      returnFeild: [
        "id",
        { name: 'order_id', aliasName: "orderId" },
        { name: 'create_time', aliasName: "createTime" },
        "remark",
        "state",
        "address_json"
      ],
      where: [
        { key: 'customer', sqlVal: customer }
      ],
      otherSql: 'ORDER BY id DESC'
    }

    state && config.where.push({
      key: 'state', sqlVal: state
    })
    const sql = renderSelectSql(config)
    console.log('getOrderListSql', sql);

    return this.query<OrderListType>(sql)
  }
}